/**
 * Copyright (C) 2012-2013 jumei, Inc.
 * RPC.java
 * 2015年6月26日
 */
package org.goface.rpc;

import java.util.Collection;

import org.goface.rpc.net.ServerSideConnectionManager;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.goface.rpc.conf.DefaultServiceConfigureCenter;
import com.goface.rpc.conf.ServiceConfigure;
import com.goface.rpc.conf.ServiceConfigureCenter;
import com.google.common.net.HostAndPort;

/**
 * 系统启动的入口类
 *
 * @author jm110
 */
public class RPC {
    private static ClassPathXmlApplicationContext ctx;
    private static ServiceConfigureCenter configureCenter;

    public static void init() {
        if (ctx != null) {
            // 防止重复启动
            return;
        }
        // 初始化spring context
        ctx = new ClassPathXmlApplicationContext(new String[] { "META-INF/base.xml", "service.xml" });

        // 启动服务端
        configureCenter = DefaultServiceConfigureCenter.getInstance();
        startServerSide(configureCenter);
    }

    public static ServiceConfigureCenter getServiceConfigureCenter() {
        return configureCenter;
    }

    public static Object getBean(String beanId) {
        Object instance = null;
        if (ctx != null) {
            instance = ctx.getBean(beanId);
        }
        return instance;

    }

    // 暂时先用单线程启动
    public static void startServerSide(ServiceConfigureCenter configureCenter) {
        Collection<ServiceConfigure> services = configureCenter.getAllServiceConfigure();
        ServerSideConnectionManager connMgr = ServerSideConnectionManager.getInstance();
        for (ServiceConfigure service : services) {
            if (!service.isClientService()) {
                String serviceBinding = service.getServiceBinding();
                HostAndPort hostAndPort = HostAndPort.fromString(serviceBinding);
                connMgr.startServer(hostAndPort);
            }
        }

    }

    public static void destroy() {
        if (ctx != null) {
            ctx.destroy();
        }

    }

}
